import React, { useState } from 'react'
import { Card, Input, Button, Spin, message } from 'antd';
import { UserSwitchOutlined, KeyOutlined } from '@ant-design/icons'
import '../static/css/Login.css'
import axios from 'axios'
import servicePath from '../api'


const Login = (props) => {
    const [userName, setUserName] = useState('')
    const [password, setPassword] = useState('')
    const [isLoading, setIsLoading] = useState(false)

    const checkLogin = () => {
        setIsLoading(true)
        if (!userName) {
            message.error('用户名不能为空')
            setIsLoading(false)
            return false
        }
        if (!password) {
            message.error('密码不能为空')
            setIsLoading(false)
            return false
        }
        let data = {
            userName,
            password
        }
        axios({
            method: 'post',
            url: servicePath.checkLogin,
            data,
            withCredentials: true
        }).then(res => {
            console.log(res.data.data)
            if (res.data.data === '登录成功') {
                setTimeout(() => {
                    setIsLoading(false)
                    localStorage.setItem('openId', res.data.openId)
                    props.history.push('/index/')
                }, 1000);
            } else {
                setTimeout(() => {
                    message.error('用户名密码错误')
                    setIsLoading(false)
                }, 1000);
            }
        }).catch(error => {
            console.log('checkLogin:', error)
        })
    }

    return (
        <div className="ovfl">
            <div className="login-div">
                <Spin tip="Loading..." spinning={isLoading}>
                    <Card title="Blog System" hoverable bordered={true} style={{ width: 400 }} >
                        <Input
                            id="userName"
                            size="large"
                            placeholder="Enter your userName"
                            prefix={<UserSwitchOutlined />}
                            onChange={(e) => { setUserName(e.target.value) }}
                        />
                        <br /><br />
                        <Input.Password
                            id="password"
                            size="large"
                            placeholder="Enter your password"
                            prefix={<KeyOutlined />}
                            onChange={(e) => { setPassword(e.target.value) }}
                        />
                        <br /><br />
                        <Button type="primary" size="large" block onClick={checkLogin} > Login in </Button>
                    </Card>
                </Spin>
            </div>
        </div>
    )
}

export default Login